package com.su.lightthings.viewmodel

import android.content.Context
import android.os.Build
import android.os.Environment
import android.os.Handler
import android.os.Looper
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.blankj.utilcode.util.LanguageUtils
import com.blankj.utilcode.util.ToastUtils
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.jeremyliao.liveeventbus.LiveEventBus
import com.su.lightthings.bean.DeviceVersionBean
import com.su.lightthings.bean.HomeFutureWeatherBean
import com.su.lightthings.bean.HomeWeatherBean
import com.su.lightthings.bean.HomeZoneBean
import com.su.lightthings.bean.PermissionResultBean
import com.su.lightthings.update.PgyUpdateChecker.UpdateInfo
import com.su.lightthings.utils.Cons
import java.util.TimeZone

class CommonViewModel : ViewModel() {
    companion object {
        private const val TAG = "CommonViewModel"

        val INSTANCE: CommonViewModel by lazy {
            CommonViewModel()
        }
    }

    //天气信息
    val weather = HomeWeatherBean()

    //未来天气信息
    val futureWeather = HomeFutureWeatherBean()

    //位置信息
    val zone = HomeZoneBean()

    //版本信息
    val version = MutableLiveData(DeviceVersionBean())

    //蓝牙开关状态
    val btState = MutableLiveData(false)

    //更新信息
    var hasCheckVersion = false
    var updateInfo: UpdateInfo? = null

    val heartDirectory: String =
        "${Environment.getExternalStorageDirectory().absolutePath}/${Cons.Common.APP_UPDATE_FILE_DIR_NAME}/heart.txt"
    val sleepDirectory: String =
        "${Environment.getExternalStorageDirectory().absolutePath}/${Cons.Common.APP_UPDATE_FILE_DIR_NAME}/sleep.txt"

    //时区
    var timeZoneRawOffset: Int? = null

    fun getSystemLanguageIndex(): Int = when (LanguageUtils.getSystemLanguage().toString()) {
        "zh_CN" -> 0
        else -> -1
    }

    fun getTimeZoneRawOffset(): Int {
        if (timeZoneRawOffset == null) {
            timeZoneRawOffset = TimeZone.getDefault().rawOffset
        }
        return timeZoneRawOffset as Int
    }


    /**
     * 获取权限管理器
     * @param id 权限标识 1.蓝牙 2.相机 3.电话 4.通知
     */
    fun doPermissionTask(id: Int, context: Context) {
        when (id) {
            0 -> getBtPermission(context)
            1 -> getCameraPermission(context)
            2 -> getPhonePermission(context)
            3 -> getNotificationPermission(context)
            4 -> getLocaltionPermission(context)
        }
    }
    /**
     * 获取权限管理器
     * @param id 权限标识 1.蓝牙 2.相机 3.电话 4.通知
     */
    fun doPermissionTask(id: Int, context: Context,callback: OnPermissionCallback) {
        when (id) {
            0 -> getBtPermission(context,callback)
            1 -> getCameraPermission(context)
            2 -> getPhonePermission(context)
            3 -> getNotificationPermission(context)
            4 -> getLocaltionPermission(context)
        }
    }

    /**
     * 获取蓝牙权限
     */
    private fun getBtPermission(context: Context) {
        val delayMillis: Long = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) 2000 else 0
        Handler(Looper.myLooper()!!).postDelayed({
            XXPermissions.with(context).permission(Permission.BLUETOOTH_SCAN)
                .permission(Permission.BLUETOOTH_CONNECT).permission(Permission.BLUETOOTH_ADVERTISE)
                .permission(Permission.ACCESS_FINE_LOCATION)
                .permission(Permission.ACCESS_COARSE_LOCATION)
//                .interceptor(PermissionInterceptor())
                .request(object : OnPermissionCallback {
                    override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                        if (!allGranted) {
                            ToastUtils.showShort("获取部分蓝牙权限成功，但部分权限未正常授予")
                            return
                        }
//                        ToastUtils.showShort("蓝牙权限获取成功")
                        sendPermissionEvent(

                            PermissionResultBean(
                                Cons.LiveDataBus.PERMISSION_BT_INDEX,
                                Cons.LiveDataBus.GET_PERMISSION_OK
                            )
                        )
                    }

                    override fun onDenied(
                        permissions: MutableList<String>, doNotAskAgain: Boolean
                    ) {
                        if (doNotAskAgain) {
                            Log.d(TAG, "被永久拒绝授权，请手动授予相机权限")
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(
                                context, permissions
                            )
                        } else {
                            ToastUtils.showShort("获取蓝牙权限失败")
                        }
                    }
                })
        }, delayMillis)
    }
    /**
     * 获取蓝牙权限
     */
    private fun getBtPermission(context: Context ,callback:OnPermissionCallback) {
        val delayMillis: Long = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) 2000 else 0
        Handler(Looper.myLooper()!!).postDelayed({
            XXPermissions.with(context).permission(Permission.BLUETOOTH_SCAN)
                .permission(Permission.BLUETOOTH_CONNECT).permission(Permission.BLUETOOTH_ADVERTISE)
                .permission(Permission.ACCESS_FINE_LOCATION)
                .permission(Permission.ACCESS_COARSE_LOCATION)
//                .interceptor(PermissionInterceptor())
                .request(callback)
        }, delayMillis)
    }

    /**
     * 获取摄像头权限
     */
    private fun getCameraPermission(context: Context) {
        val delayMillis: Long = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) 2000 else 0
        Handler(Looper.getMainLooper()).postDelayed({
            XXPermissions.with(context).permission(Permission.CAMERA)
//                .interceptor(PermissionInterceptor())
                .request(object : OnPermissionCallback {
                    override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                        if (!allGranted) {
                            ToastUtils.showShort("相机权限获取失败")
                            return
                        }
//                        ToastUtils.showShort("相机权限获取成功")
                        sendPermissionEvent(
                            PermissionResultBean(
                                Cons.LiveDataBus.PERMISSION_CAMERA_INDEX,
                                Cons.LiveDataBus.GET_PERMISSION_OK
                            )
                        )
                    }

                    override fun onDenied(
                        permissions: MutableList<String>, doNotAskAgain: Boolean
                    ) {
                        if (doNotAskAgain) {
                            Log.d(TAG, "被永久拒绝授权，请手动授予相机权限")
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(
                                context, permissions
                            )
                        } else {
                            ToastUtils.showShort("获取相机权限失败")
                        }
                    }
                })
        }, delayMillis)
    }

    /**
     * 获取电话控制权限
     */
    private fun getPhonePermission(context: Context) {
        val delayMillis: Long = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) 2000 else 0
        Handler(Looper.myLooper()!!).postDelayed({
            XXPermissions.with(context)
                .permission(Permission.READ_PHONE_STATE)
//                .permission(Permission.READ_CALL_LOG)
                .permission(Permission.ANSWER_PHONE_CALLS)
                .permission(Permission.READ_CONTACTS)
//                .interceptor(PermissionInterceptor())
                .request(object : OnPermissionCallback {
                    override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                        if (!allGranted) {
                            ToastUtils.showShort("电话权限获取失败")
                            Log.d(TAG, "电话权限未全部获取: $permissions")
                            return
                        }
//                        ToastUtils.showShort("电话权限获取成功")
                        sendPermissionEvent(
                            PermissionResultBean(
                                Cons.LiveDataBus.PERMISSION_PHONE_INDEX,
                                Cons.LiveDataBus.GET_PERMISSION_OK
                            )
                        )
                    }

                    override fun onDenied(
                        permissions: MutableList<String>, doNotAskAgain: Boolean
                    ) {
                        Log.d(TAG, "电话拒绝: $permissions")
                        sendPermissionEvent(
                            PermissionResultBean(
                                Cons.LiveDataBus.PERMISSION_PHONE_INDEX,
                                Cons.LiveDataBus.GET_PERMISSION_FAILED
                            )
                        )
                        if (doNotAskAgain) {
                            Log.d(TAG, "被永久拒绝授权，请手动授予电话权限")
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(
                                context, permissions
                            )
                        } else {
                            ToastUtils.showShort("获取电话权限失败")
                        }
                    }
                })

        }, delayMillis)
    }

    /**
     * 获取消息通知权限
     */
    private fun getNotificationPermission(context: Context) {
        val delayMillis: Long = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) 2000 else 0
        Handler(Looper.myLooper()!!).postDelayed({
            XXPermissions.with(context)
                .permission(Permission.BIND_NOTIFICATION_LISTENER_SERVICE)
//                .interceptor(PermissionInterceptor())
                .request(object : OnPermissionCallback {
                    override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                        if (!allGranted) {
                            ToastUtils.showShort("消息通知权限获取失败")
                            sendPermissionEvent(
                                PermissionResultBean(
                                    Cons.LiveDataBus.PERMISSION_NOTIFICATION_INDEX,
                                    Cons.LiveDataBus.GET_PERMISSION_FAILED
                                )
                            )
                            return
                        }
//                        ToastUtils.showShort("消息通知权限获取成功")
                        sendPermissionEvent(
                            PermissionResultBean(
                                Cons.LiveDataBus.PERMISSION_NOTIFICATION_INDEX,
                                Cons.LiveDataBus.GET_PERMISSION_OK
                            )
                        )
                    }

                    override fun onDenied(
                        permissions: MutableList<String>, doNotAskAgain: Boolean
                    ) {
                        sendPermissionEvent(
                            PermissionResultBean(
                                Cons.LiveDataBus.PERMISSION_NOTIFICATION_INDEX,
                                Cons.LiveDataBus.GET_PERMISSION_FAILED
                            )
                        )

                        if (doNotAskAgain) {
                            Log.d(TAG, "被永久拒绝授权，请手动授予消息权限")
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(
                                context, permissions
                            )
                        } else {
                            ToastUtils.showShort("获取消息通知权限失败")
                        }
                    }
                })

        }, delayMillis)
    }

    /**
     * 获取地理位置权限
     */
    private fun getLocaltionPermission(context: Context) {
        val delayMillis: Long = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) 2000 else 0
        Handler(Looper.myLooper()!!).postDelayed({
            XXPermissions.with(context)
                .permission(Permission.ACCESS_FINE_LOCATION)
                .permission(Permission.ACCESS_COARSE_LOCATION)
//                .interceptor(PermissionInterceptor())
                .request(object : OnPermissionCallback {
                    override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                        if (!allGranted) {
                            ToastUtils.showShort("位置权限获取失败")
                            return
                        }
//                        ToastUtils.showShort("位置权限获取成功")
                        sendPermissionEvent(
                            PermissionResultBean(
                                Cons.LiveDataBus.PERMISSION_LOCATION_INDEX,
                                Cons.LiveDataBus.GET_PERMISSION_OK
                            )
                        )
                    }

                    override fun onDenied(
                        permissions: MutableList<String>, doNotAskAgain: Boolean
                    ) {
                        if (doNotAskAgain) {
                            Log.d(TAG, "被永久拒绝授权，请手动授予相机权限")
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(
                                context, permissions
                            )
                        } else {
                            ToastUtils.showShort("获取消息通知权限失败")
                        }
                    }
                })

        }, delayMillis)
    }

    /**
     * 权限事件申请结果事件总线分发
     */
    private fun sendPermissionEvent(event: PermissionResultBean) =
        LiveEventBus.get(Cons.LiveDataBus.GET_PERMISSION_RESULT, PermissionResultBean::class.java)
            .post(event)


}